package com.wealth.system.web.controller;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.system.entity.Corporation;
import com.wealth.system.entity.User;
import com.wealth.system.service.ICorpService;
import com.wealth.system.service.ShiroUser;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;
import iaas.utils.CommonUtil;
import iaas.utils.RedirectMessage;

/**
 * 登录
 * @author chan
 */

@Controller
@RequestMapping(value="/login")
public class LoginController extends BaseController{
	
	Logger logger = Logger.getLogger(LoginController.class);
	
	@Autowired
	private ICorpService corpService;
	
	/**
	 * 用户登录
	 */	
	@Log(method="登录")
	@RequestMapping(value="",method = RequestMethod.POST)
	public String login(User user,HttpSession session,HttpServletRequest request,Model model,RedirectAttributes redirectAttributes){
		
//		String code = (String) session.getAttribute("validateCode");
//		String summitCode = request.getParameter("validateCode");
		String error = null;
		UsernamePasswordToken token = null;
		Subject users = null;
		try { 
			/*
			 if(StringUtils.isEmpty(summitCode) || !StringUtils.equals(code.toLowerCase(), summitCode.toLowerCase())){
				 model.addAttribute("msg", "验证码错误");
				 return "/login";
			 }
			 */
			 users = SecurityUtils.getSubject();
			 token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
			 
			 token.setRememberMe(true);
			 users.login(token); 
			//登录成功访问首页
			 
			 //判断企业是否过期
			 //企业ID
			 Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();	
			 Corporation corp = corpService.get(corpid);
			 if(CommonUtil.compareTimes(corp.getOvertime(), new Date())<0){
		    		model.addAttribute("msg", "企业账户过期，请联系管理员解决");
					return "/login";
			 }
			 //判断企业状态 
			 if(corp.getStatus()==StatusEnum.STOP.getValue()){
		    		model.addAttribute("msg", "企业被停用，请联系管理员解决");
					return "/login";
			 }
			//判断用户状态 
			 int status = ShiroUser.getInstance().getUser().getStatus();
			 if(status==StatusEnum.DELETE.getValue()){
		    		model.addAttribute("msg", "用户不存在，请联系管理员解决");
					return "/login";
			 }
			 if(status==StatusEnum.STOP.getValue()){
		    		model.addAttribute("msg", "用户被停用，请联系管理员解决");
					return "/login";
			 }
			 int days = CommonUtil.compareDay(corp.getOvertime(), new Date());
			 if(days < 30){
				 redirectAttributes.addFlashAttribute("message",
						RedirectMessage.setShowTipSuccess(("您的账户距离过期时间还有【"+(days)+"】天，请在过期前续费，以免造成不必要的损失！") ) );
			 }
			
	     } catch (UnknownAccountException e) {  
	            error = "用户名/密码错误";  
	     } catch (IncorrectCredentialsException e) {  
	            error = "用户名/密码错误";  
	     } catch (AuthenticationException e) {  
	            //其他错误，比如锁定，如果想单独处理请单独catch处理  
	            error = "其他错误：" + e.getMessage();  
	     }catch (NullPointerException e) {
	    	 error = "验证码错误";  
	     }catch (Exception e) {
	    	 error = "系统错误,请联系管理员" ;  
		} 
		
		//错误了，返回登录页面  
	     if(error != null) {
	    	if(token!=null){
	    		token.clear();
	    	}
	        model.addAttribute("msg", error);
			return "login";
	     } 
    	
	     return "redirect:/manage/index";
	}
	
}
